package com.polaris.live.dialog.luckybag

import android.content.Context
import android.view.ViewGroup
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.google.common.primitives.Ints.min
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.cache.CommonCache
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.DialogLuckyBagSendBinding
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.net.chatService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.go_resp.luckybag.LuckyBagSendBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.XPopupUtils
import kotlin.math.max

/**
 * 福袋发送弹窗
 *
 * @author Created by lucas on 2024/6/11 03:02
 */
class LuckyBagSendDialog(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val mLiveId: Long?,
) : BottomPopupView(context) {

    private lateinit var mBinding: DialogLuckyBagSendBinding

    private val mBombNumViews by lazy {
        listOf(
            mBinding.ivBomb0,
            mBinding.ivBomb1,
            mBinding.ivBomb2,
            mBinding.ivBomb3,
            mBinding.ivBomb4,
            mBinding.ivBomb5,
            mBinding.ivBomb6,
            mBinding.ivBomb7,
            mBinding.ivBomb8,
            mBinding.ivBomb9,
        )
    }
    private val mLuckyBagCoinRange by lazy {
        getLuckyBagCoinRange()
    }

    private var mSelectedBombNum = 0

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_lucky_bag_send
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogLuckyBagSendBinding.bind(popupImplView)
        mBinding.etContent.hint = StringUtils.getString(
            string.input_lucky_bag_diamond_num,
            mLuckyBagCoinRange.first,
            mLuckyBagCoinRange.second
        )
        mBinding.tvCoin.text = "${UserManager.getUser().account?.userCoins ?: 0}" + " "
        mBombNumViews.forEachIndexed { index, view ->
            view.isSelected = false
            view.setOnSingleClickListener {
                if (view.isSelected) return@setOnSingleClickListener
                view.isSelected = true
                mBombNumViews[mSelectedBombNum].isSelected = false
                mSelectedBombNum = index

                CommonCache.saveLuckyBagBombNum(index)
            }
        }

        mSelectedBombNum = min(max(CommonCache.getLuckyBagBombNum(), 0), mBombNumViews.size - 1)
        mBombNumViews[mSelectedBombNum].isSelected = true

        CommonCache.getLuckyBagSendCoin()?.also {
            mBinding.etContent.setText(it.toString())
            mBinding.etContent.setSelection(it.toString().length)
        }

        mBinding.tvSubmit.setOnSingleClickListener {
            val coins = mBinding.etContent.text?.toString()?.toLongOrNull()
            if (coins == null) {
                ToastGravity.showGravity(string.lucky_bag_edit_empty_bomb_num)
                return@setOnSingleClickListener
            } else if (coins < mLuckyBagCoinRange.first || coins > mLuckyBagCoinRange.second) {
                ToastGravity.showGravity(
                    StringUtils.getString(
                        string.lucky_bag_edit_bomb_num_error,
                        mLuckyBagCoinRange.first,
                        mLuckyBagCoinRange.second
                    )
                )
                return@setOnSingleClickListener
            }

            CommonCache.saveLuckyBagSendCoin(coins)

            val request = LuckyBagSendBean(
                mLiveId,
                coins,
                mSelectedBombNum
            )

            mViewModel.requestLoading({ chatService.sendLuckyBag(request) }, {
                dismiss()
            }, {
                if (it.errCode == CommonConst.ErrorCode.SENDGIFT) {
                    GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }
            })
        }

        mBinding.ivLuckyBagWhat.setOnSingleClickListener {
            XPopupUtils.showPopup(LuckyBagDescDialog(context), { hasShadowBg(true) })
        }

        mBinding.tvCoin.setOnSingleClickListener {
            GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
        }

        ImNoticeManager.observeAccountChange(this) {
            mBinding.tvCoin.text = "${UserManager.getUser().account?.userCoins ?: 0}" + " "
        }

        val span = SpanUtils.with(mBinding.tvPrompt)
            .appendImage(R.drawable.lucky_send_detail_icon, SpanUtils.ALIGN_CENTER)
            .append(" ${StringUtils.getString(string.lucky_send_detail_text)}")
            .create()
        mBinding.tvPrompt.text = span

        NavigationBarUtils.setNavigationHeight(mBinding.viewBottomPleaseHolder) { view, height ->
            val layoutParams = view.layoutParams as ViewGroup.LayoutParams
            layoutParams.height = height
            mBinding.viewBottomPleaseHolder.layoutParams = layoutParams
        }
    }

    private fun getLuckyBagCoinRange(): Pair<Int, Int> {
        val str = AppConfigManager.getConfig(CommonConst.Configs.luckyBagCoins)

        val split = str?.split(":")
        return if (split != null && split.size == 2) {
            val start = split[0].toIntOrNull() ?: 100
            val end = split[1].toIntOrNull() ?: 1000
            start to end
        } else {
            Pair(100, 1000)
        }
    }
}